﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPort通信
{
    public class HexHelper
    {
        /// <summary>
        ///判断是否为16进制字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsHexString(string input)
        {
            // 空值或空字符串直接返回false
            if (string.IsNullOrEmpty(input))
                return false;
            // 检查所有字符是否在十六进制字符范围内
            return input.All(c =>
                (c >= '0' && c <= '9') ||
                (c >= 'A' && c <= 'F') ||
                (c >= 'a' && c <= 'f'));
        }

        /// <summary>
        ///判断是否为16进制字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsHexString(char c)
        {
            // 检查所有字符是否在十六进制字符范围内
            return (c >= '0' && c <= '9') ||
                (c >= 'A' && c <= 'F') ||
                (c >= 'a' && c <= 'f');
        }

        /// <summary>
        ///将ASC1I码字符串转换成16进制字符串
        /// </summary>
        /// <param name="asciiString"></param>
        /// <returns></returns>
        public static string AsciiToHex(string asciiString)
        {
            if (string.IsNullOrEmpty(asciiString))
                return string.Empty;

            StringBuilder hexBuilder = new StringBuilder(asciiString.Length * 2);

            foreach (char c in asciiString)
            {
                // 将字符转换为字节（ASCII值）
                byte asciiValue = (byte)c;

                // 将字节转换为两位十六进制字符串
                hexBuilder.Append(asciiValue.ToString("X2"));
            }

            return hexBuilder.ToString();
        }

        /// <summary>
        ///将16进制字符串转换成ASCII码字符串
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static string HexToAscii(string hexString)
        {
            if (string.IsNullOrEmpty(hexString))
                return string.Empty;

            // 预处理：移除可能存在的空格和前缀
            hexString = hexString.Replace(" ", "").Replace("0x", "").Replace("0X", "");

            // 验证十六进制格式
            if (hexString.Length % 2 != 0)
                throw new ArgumentException("十六进制字符串长度必须为偶数");

            byte[] bytes = new byte[hexString.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                string hexByte = hexString.Substring(i * 2, 2);

                if (!byte.TryParse(hexByte, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out bytes[i]))
                {
                    throw new ArgumentException($"无效的十六进制字符: '{hexByte}'");
                }
            }

            return Encoding.ASCII.GetString(bytes);
        }

        /// <summary>
        /// 获取16进制字符串的字节数
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static int GetHexByteCount(string hexString)
        {
            if (string.IsNullOrEmpty(hexString))
                return 0;

            // 统计有效的十六进制字符数量（忽略空格和分隔符）
            int validCharCount = 0;
            foreach (char c in hexString)
            {
                if (IsHexString(c))
                    validCharCount++;
            }

            // 处理前缀（0x/0X）
            if (hexString.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                // 减去前缀中的有效字符（0和x/X）
                validCharCount = Math.Max(0, validCharCount - 2);
            }

            // 每两个十六进制字符对应一个字节
            return validCharCount / 2;
        }

        /// <summary>
        /// 单个16进制数转字节
        /// </summary>
        /// <param name="hexChar"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static byte HexCharToByte(char hexChar)
        {
            // 检查输入字符是否为有效十六进制字符
            if ((hexChar >= '0' && hexChar <= '9') ||
                (hexChar >= 'A' && hexChar <= 'F') ||
                (hexChar >= 'a' && hexChar <= 'f'))
            {
                // 处理数字字符
                if (hexChar <= '9')
                    return (byte)(hexChar - '0');

                // 处理大写字母
                if (hexChar <= 'F')
                    return (byte)(hexChar - 'A' + 10);

                // 处理小写字母
                return (byte)(hexChar - 'a' + 10);
            }

            throw new ArgumentException($"无效的十六进制字符: '{hexChar}'");
        }

        /// <summary>
        /// 16进制字符串转换成字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] HexStringToByteArray(string hex)
        {
            if (string.IsNullOrEmpty(hex))
                return Array.Empty<byte>();

            // 预处理：移除空格和前缀
            string cleanHex = hex
                .Replace(" ", "")
                .Replace("\t", "")
                .Replace("\n", "")
                .Replace("0x", "")
                .Replace("0X", "");

            // 验证长度
            if (cleanHex.Length % 2 != 0)
                throw new ArgumentException("十六进制字符串长度必须为偶数");

            // 转换
            byte[] bytes = new byte[cleanHex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                string byteString = cleanHex.Substring(i * 2, 2);
                bytes[i] = Convert.ToByte(byteString, 16);
            }

            return bytes;
        }

        /// <summary>
        /// 字节数组转换成16进制转字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteArrayToHexString(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                return string.Empty;

            StringBuilder hex = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                hex.AppendFormat("{0:X2}", b);
            }
            return hex.ToString();
        }

        /// <summary>
        /// 拼接字节数组
        /// </summary>
        /// <param name="arrays"></param>
        /// <returns></returns>
        public static byte[] ConcatenateBytes(params byte[][] arrays)
        {
            // 计算总长度
            int totalLength = 0;
            foreach (byte[] array in arrays)
            {
                if (array != null) totalLength += array.Length;
            }

            // 创建结果数组并复制数据
            byte[] result = new byte[totalLength];
            int offset = 0;

            foreach (byte[] array in arrays)
            {
                if (array != null && array.Length > 0)
                {
                    Array.Copy(array, 0, result, offset, array.Length);
                    offset += array.Length;
                }
            }

            return result;
        }
    }
}